﻿using System;
using System.Collections.Generic;
using Auth.Domain.TableEntity;
using Auth.Repository.IRepositories;
using Auth.SqlSugar;
using Auth.SqlSugar.IocManager;
using Auth.SqlSugar.Repositories;
using Auth.Utility;
using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace Auth.Repository.Repositories
{
    public class RoleRepository : BaseRepository<roles>, IRoleRepository
    {
        public RoleRepository()
        {
        }

        /// <summary>
        /// 根据角色获取权限
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllMenuListByRole(string roleId)
        {
            using (SqlSugarClient dbClient = DbInstance.GetInstance())
            {
                var res = dbClient.Queryable<rolemenus>().Where(s => s.RoleId == roleId).WithCacheIF(RedisCache.UseCache).Select(s => s.MenuId).ToList();
                return res;
            }
        }

        /// <summary>
        /// 更新角色权限关联关系
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <param name="roleMenus">角色菜单集合</param>
        /// <returns></returns>
        public bool UpdateRoleMenu(string roleId, List<rolemenus> roleMenus)
        {
            using (SqlSugarClient dbClient = DbInstance.GetInstance())
            {
                try
                {
                    dbClient.Ado.BeginTran();
                    var oldDatas = dbClient.Queryable<rolemenus>().Where(it => it.RoleId == roleId).WithCacheIF(RedisCache.UseCache).ToList();
                    if (RedisCache.UseCache)
                    {
                        dbClient.Deleteable(oldDatas).RemoveDataCache().ExecuteCommand();
                        return dbClient.Insertable(roleMenus).RemoveDataCache().ExecuteCommand() > 0;
                    }
                    else {
                        dbClient.Deleteable(oldDatas).ExecuteCommand();
                        return dbClient.Insertable(roleMenus).ExecuteCommand() > 0;
                    }
                    
                }
                catch (Exception ex)
                {
                    dbClient.Ado.RollbackTran();
                    throw new Exception(ex.Message);
                }
            }
        }

        /// <summary>
        /// 根据用户id获取角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<userroles> GetRoleByUser(string userId)
        {
            using (SqlSugarClient dbClient = DbInstance.GetInstance())
            {
                return dbClient.Queryable<userroles>().Where(s => s.UserId == userId).WithCacheIF(RedisCache.UseCache).ToList();
            }
        }
    }
}